package com.cxf.windex.biz;

import com.cxf.windex.base.biz.BaseBiz;
import com.cxf.windex.base.constant.UserConstant;
import com.cxf.windex.base.util.FileFilterTool;
import com.cxf.windex.base.util.IdUtil;
import com.cxf.windex.base.util.ImageBase64;
import com.cxf.windex.base.util.ShorUrlUtil;
import com.cxf.windex.entity.JsContents;
import com.cxf.windex.entity.JsNotes;
import com.cxf.windex.mapper.JsContentsMapper;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author chenxf
 * @date 3/15/2018
 * @description
 */
@Slf4j
@Service
public class JsContentsBiz extends BaseBiz<JsContentsMapper, JsContents> {

    /**
     * 文件存放 路径
     */
    @Value("${upload.path}")
    private String uploadPath;

    /**
     * 文件访问路径
     */
    @Value("${upload.url}")
    private String uploadUrl;

    @Value("${upload.uri}")
    private String uploadUri;
    /**
     * 文库列表
     *
     * @param limit 数量
     * @param offset 页码
     * @param orderStr  排序(升序或者降序)
     * @param title 标题
     * @param type 类型
     * @param range 0商家 1村长
     * @return
     */
    public List<JsContents> list(int limit, int offset, String orderStr,String title,String type,String range) {
        Example example = new Example(JsContents.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(title)){
            criteria.andLike("title",  "%"+title+"%" );
        }
        criteria .andEqualTo("range", range);
        if(StringUtils.isNotBlank(type)){
            criteria .andEqualTo("type", type);
        }
        example.setOrderByClause("order_no asc,crt_time " + orderStr);
        PageHelper.startPage(offset, limit);
        return selectByExample(example);
    }

    /**
     * 保存文章
     * @param jsContents
     */
    public void save(JsContents jsContents){
        jsContents.setId(UserConstant.ARTICLE_ID_PREX+new IdUtil(5,1).nextId());
        insertSelective(jsContents);
    }

    public Map base64Upload(String fileType, String base64){
        Map resultMap = new HashMap();
        if(StringUtils.isBlank(fileType)){
            resultMap.put("code","-1");
            resultMap.put("msg","请传入文件类型");
            return resultMap;
        }
        if(StringUtils.isBlank(base64)){
            resultMap.put("code","-1");
            resultMap.put("msg","请传入base64文件");
            return resultMap;
        }

        String uuid= ShorUrlUtil.shortUrl(UUID.randomUUID().toString())[0] ;
        String webRoot  = uploadPath  + File.separator  +"idcard" + File.separator+uuid+ File.separator;
        String saveUrl = uploadUrl+ "/" +"idcard"+ "/"+uuid+ "/"+ uuid+"."+fileType;
        File directoryFile = new File(webRoot);
        if(!directoryFile.exists()) {
            directoryFile.mkdirs();
        }
        ImageBase64.base64StringToImage(base64,fileType,webRoot+uuid+"."+fileType);
        resultMap.put("filename", uuid+"."+fileType);
        resultMap.put("saveUrl",saveUrl);
        resultMap.put("code","0");
        return resultMap;
    }

    public Map upload(MultipartFile file, String type){
        Map resultMap = new HashMap();
        if (file != null) {
            Map<String, Object> savePcMap = saveFile(resultMap, file, type);
            if (savePcMap != null) {
                if (savePcMap.get("code").equals("0")) {
                    Map fileMap = new HashMap();
                    fileMap.put("src", uploadUri+savePcMap.get("saveUrl"));
                    resultMap.putAll(savePcMap);
                    resultMap.put("data", fileMap);
                    return resultMap;
                } else {
                    return savePcMap;
                }
            }
        }
        return resultMap;
    }

    /**
     * 保存图片 返回Map
     * @param resultMap 返回结果
     * @param file 文件
     * @param type 文件类型
     * @return
     *   null 异常不处理
     *   -1  图片格式异常
     *   -2 图片保存异常
     *
     */
    public Map<String,Object> saveFile( Map<String,Object> resultMap,MultipartFile file, String type){
        if (file.isEmpty()) {
            return null;
        }
        FileFilterTool fileFilterTool=new FileFilterTool();
//        if(!fileFilterTool.accept(file.getOriginalFilename())){
//            resultMap.put("code","-1");
//            resultMap.put("msg","图片格式不正确。只能上传JPG,JPEG,GIF,PNG图片！");
//
//            return  resultMap;
//        }
        try {
            String uuid= ShorUrlUtil.shortUrl(UUID.randomUUID().toString())[0] ;
            String webRoot  = uploadPath  + File.separator  +type + File.separator+uuid+ File.separator;
            String saveUrl = uploadUrl+ "/" +type+ "/"+uuid+ "/"+ file.getOriginalFilename();

            File directoryFile = new File(webRoot);
            if(!directoryFile.exists()) {
                directoryFile.mkdirs();
            }
            log.info("save path:"+webRoot);
            Path path = Paths.get(webRoot + file.getOriginalFilename());
            Files.write(path,  file.getBytes());

            if(file.getSize()>1048576 && fileFilterTool.accept(file.getOriginalFilename())){
                Thumbnails.of(webRoot + file.getOriginalFilename()).scale(1f).outputQuality(0.25f).toFile(webRoot + file.getOriginalFilename());
            }

            resultMap.put("filename",file.getOriginalFilename());
            resultMap.put("saveUrl",saveUrl);
            resultMap.put("code","0");
            log.info("BankConfigController#saveFile processing : map= {},saveUrl={}", resultMap,resultMap.get("saveUrl"));
            return resultMap;
        } catch (IOException e) {
            log.error("BankConfigController#saveFile failed : IOException= {}", e);
            resultMap.put("code","-2");
            resultMap.put("msg","图片保存异常！");
            return resultMap;
        }

    }
}
